import { FC, useState, useEffect } from 'react';
import AvatarDropdown from '../AvatarDropdown';
import { connect, Dispatch, useModel } from 'umi';
import { Modal, message, Select, Button } from 'antd';
import { getCookie } from '@/utils/cookie';
import { getCompanys } from '@/services/common';

import styles from './index.<%= css %>';
interface IProps {
  dispatch: Dispatch;
  common: any;
}
export interface ICommonState {}

const RightContent: FC<IProps> = ({ dispatch, common }): JSX.Element => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [companys, setCompanys] = useState<[]>([]);
  const [companyId, setCompanyId] = useState<number>(0);
  const { initialState, setInitialState } = useModel('@@initialState');

  const onCompanyChange = (companyId: number) => {
    setCompanyId(companyId);
  };

  const onSwitchCompanySuccess = () => {
    if (!companyId) {
      return message.warn('请先选择企业', 1);
    }
    dispatch({
      type: 'common/switchCompany',
      payload: companys.find((item: any) => item.id === companyId),
      callback: () => {
        setInitialState({ ...initialState, token: getCookie('token') });
        setModalVisible(false);
      },
    });
  };

  useEffect(() => {
    getCompanys({ types: ['SERVER'] }).then((res: any) => {
      setCompanys(res || []);
    });
  }, []);
  const companyInfo = JSON.parse(localStorage.getItem('__cpy_curr') || '{}');
  return (
    <>
      <div className={styles.rightContent}>
        <Button
          type="text"
          disabled={companys?.length === 1}
          onClick={() => setModalVisible(true)}
        >
          {companyInfo.name}
        </Button>
        <AvatarDropdown />
      </div>

      <Modal
        title="请选择企业"
        closable={false}
        centered
        visible={modalVisible}
        onCancel={() => {
          setModalVisible(false);
        }}
        onOk={onSwitchCompanySuccess}
      >
        <Select
          placeholder="请选择企业"
          onChange={onCompanyChange}
          style={{ width: '100%' }}
        >
          {(companys || []).map(({ id, name }) => (
            <Select.Option key={id} value={id}>
              {name}
            </Select.Option>
          ))}
        </Select>
      </Modal>
    </>
  );
};
export default connect(({ common }: { common: ICommonState }) => ({ common }))(
  RightContent,
);
